package com.demo.controller;


import com.demo.entity.SysDepartment;
import com.demo.model.JsonMessage;
import com.demo.service.DepartmentService;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Controller
@Api(value = "部门管理接口")
@RequestMapping("/admin/department")
public class DepartmentController {
    @Autowired
    private DepartmentService departmentService;

    @ApiOperation(value = "添加部门")
    @PostMapping("add")
    @ResponseBody
    public JsonMessage add(SysDepartment department) {
        JsonMessage message = new JsonMessage();
        try {
            departmentService.add(department);
        } catch (Exception e) {
            message.setSuccess(false);
            message.setMessage("添加失败，部门编号已存在");
        }
        return message;
    }

    @ApiOperation(value = "查看部门")
    @GetMapping("get")
    @ResponseBody
    public JsonMessage get(String id) {
        JsonMessage msg = new JsonMessage();
        SysDepartment department = departmentService.get(id);
        msg.setData(department);
        return msg;
    }

    @ApiOperation(value = "更新部门")
    @PostMapping("save")
    @ResponseBody
    public JsonMessage save(SysDepartment department) {
        JsonMessage msg = new JsonMessage();
        departmentService.save(department);
        msg.setData("更新成功！");
        return msg;
    }

    @ApiOperation(value = "部门列表")
    @PostMapping("list")
    @ResponseBody
    public JsonMessage list(@RequestParam(defaultValue = "0") int pageIndex,
                            @RequestParam(defaultValue = "10") int pageSize) {
        JsonMessage message = new JsonMessage();
        PageInfo<SysDepartment> page = departmentService.list(pageIndex, pageSize);
        message.setData(page);
        return message;
    }

    @ApiOperation(value = "删除部门")
    @PostMapping("delete")
    @ResponseBody
    public JsonMessage delete(String id) {
        JsonMessage message = new JsonMessage();
        departmentService.remove(id);
        return message;
    }

    @ApiOperation(value = "单个部门信息")
    @PostMapping("depInfo")
    @ResponseBody
    public JsonMessage depInfo(String depId) {
        JsonMessage message = new JsonMessage();
        List<String> dep = departmentService.idInfo(depId);
        if (dep==null){
            message.setData("");
        }else {
            message.setData(dep);
        }
        return message;
    }
}
